const path = require('path')
const fs = require('fs').promises
const { createReadStream } = require('fs')
const fse = require('fs-extra')

// 验证路径是否在服务器根目录下
function validatePath(absolutePath) {
    const serverRoot = path.join(__dirname, '..');  // server 目录
    const normalizedPath = path.normalize(absolutePath);
    return normalizedPath.startsWith(serverRoot) ? normalizedPath : null;
}

async function listFiles(absolutePath) {
    const fullPath = validatePath(absolutePath);
    if (!fullPath) {
        return {
            status: 0,
            message: '无效的路径'
        }
    }
    try {
        const files = await fs.readdir(fullPath, { withFileTypes: true });
        const result = files.map(file => ({
            name: file.name,
            isDir: file.isDirectory(),
            path: path.join(absolutePath, file.name).replace(/\\/g, '/')
        }));
        return {
            status: 1,
            data: result
        }
    } catch (error) {
        return {
            status: 0,
            message: '读取目录失败'
        }
    }
}

async function downloadFile(absolutePath) {
    try {
        console.log('Validating path:', absolutePath); // 调试用
        const fullPath = validatePath(absolutePath);
        
        if (!fullPath) {
            return {
                status: 0,
                message: '无效的路径'
            };
        }

        console.log('Full path:', fullPath); // 调试用
        
        // 检查文件是否存在和是否是文件
        try {
            const stats = await fs.stat(fullPath);
            if (!stats.isFile()) {
                return {
                    status: 0,
                    message: '路径不是文件'
                };
            }
        } catch (error) {
            if (error.code === 'ENOENT') {
                return {
                    status: 0,
                    message: '文件不存在'
                };
            }
            throw error;
        }
        
        // 创建文件读取流
        return {
            status: 1,
            data: {
                filename: path.basename(fullPath),
                stream: createReadStream(fullPath)
            }
        };
    } catch (error) {
        console.error('Download file error:', error);
        return {
            status: 0,
            message: '无法访问文件: ' + error.message
        };
    }
}

async function deleteItem(absolutePath, isDir) {
    const fullPath = validatePath(absolutePath);
    if (!fullPath) {
        return {
            status: 0,
            message: '无效的路径'
        }
    }
    try {
        if (isDir) {
            await fse.remove(fullPath);
        } else {
            await fs.unlink(fullPath);
        }
        return {
            status: 1,
            message: '删除成功'
        }
    } catch (error) {
        return {
            status: 0,
            message: '删除失败'
        }
    }
}

async function createDir(absolutePath) {
    const fullPath = validatePath(absolutePath);
    if (!fullPath) {
        return {
            status: 0,
            message: '无效的路径'
        }
    }
    try {
        await fs.mkdir(fullPath, { recursive: true });
        return {
            status: 1,
            message: '创建成功'
        }
    } catch (error) {
        return {
            status: 0,
            message: '创建失败'
        }
    }
}

async function renameItem(oldPath, newPath) {
    const fullOldPath = validatePath(oldPath);
    const fullNewPath = validatePath(newPath);
    if (!fullOldPath || !fullNewPath) {
        return {
            status: 0,
            message: '无效的路径'
        }
    }
    try {
        await fs.rename(fullOldPath, fullNewPath);
        return {
            status: 1,
            message: '重命名成功'
        }
    } catch (error) {
        return {
            status: 0,
            message: '重命名失败'
        }
    }
}

module.exports = {
    listFiles,
    downloadFile,
    deleteItem,
    createDir,
    renameItem,
    validatePath  // 导出验证函数供路由使用
}
